import { Component, ElementRef, ViewChild, AfterViewInit } from '@angular/core';

@Component({
  selector: 'app-multonlineexcel',
  standalone: true, //是否为独立组件
  imports: [],
  templateUrl: './multonlineexcel.component.html',
  styleUrls: ['./multonlineexcel.component.less']
})

export class multOnlineExcelComponent implements AfterViewInit{
  
  @ViewChild('luckysheet') luckysheet: ElementRef;
  options=[]
  sheet:any= {}
  dataSetLists= []
  dataForm= {
    tableld: null
  }
  sheetData:any= [{}]
  reportExcelDto= {
    jsonStr: "",   //报表json串(存放模版)
    setIds: "",  //数据集ids(使用|分割)
    // setParam: "",
    reportId: "",  //报告id(关联report表的report_id)
    reportExcelId: null,  //根据reportExcelId是否为空，判断是新增操作 或 更新操作
  }
  rightForm= {
    coordinate: "",
    value: "",
    r: "",
    c: "",
    auto: false,
    autoIsShow: false,
  }
  formPrintSetting= {
    size: "",
    pixel1: "",
    pixel2: "",
  }
  outerVisible= false
  printVisible= false
  pop= false
  setCode= null
  draggableFieldLabel= {
    v: null,
    m: null
  }
  dialogVisible= false
  dialogBarCode= false
  paperList= []
  // 纸张标识
  paper= ""
  // 纸张宽高
  width= ""
  height= ""
  // 清晰度
  definition= ""
  // 是否套打
  isBackend= ""
  dpi= ""
  pxWidth= ""
  pxHeight= ""
  show= false
  config= ""
  settings= {}
  qrCodeList= []
  moveDataelse= {
    x: null,
    y: null,
  }
  _window = window as any

  ngAfterViewInit(){
  this.createSheet()
  }
      //初始化表格
  createSheet () {
    const options:any = {
      container: "luckysheet", // 设定DOM容器的id
      title: "", // 设定表格名称
      lang: "zh", // 设定表格语言
      plugins: ["chart"],
      hook: {
        cellDragStop:  (cell, postion, sheetFile, ctx, event)=> {
          this._window.luckysheet.setCellValue(
            postion.r,
            postion.c,
            this.draggableFieldLabel
          )
        },
        cellMousedown:  (cell, postion, sheetFile, ctx)=> {
          //单元格点击事件
          this.rightForm.coordinate = postion.r + "," + postion.c
          this.rightForm.r = postion.r
          this.rightForm.c = postion.c
          this.rightForm.value = cell == null ? "" : cell.m
          this.rightForm.autoIsShow = true
          //判断单元格是否是静态数据并且是合并单元格
          if (
            cell != null &&
            (cell.v == undefined || cell.v.indexOf("#{") === -1)
          ) {
            this.rightForm.autoIsShow = true
            if (cell.auto != null && cell.auto == "1") {
              this.rightForm.auto = true
            } else {
              this.rightForm.auto = false
            }
          } else {
            this.rightForm.auto = false
          }
        },
        workbookCreateAfter:  ()=> {
          this.sheetData?.forEach(sheet => {
            sheet.celldata?.forEach(item => {
              this._window.luckysheet.setCellValue(
                item.r,
                item.c,
                {
                  m: item.v.m,
                  v: item.v.v
                }
              )
            })
          })
        }
      },
      data: [
        {
          name: "report", //工作表名称
          color: "", //工作表颜色
          index: 0, //工作表索引
          status: 1, //激活状态
          order: 0, //工作表的下标
          hide: 0, //是否隐藏
          row: 36, //行数
          column: 18, //列数
          defaultRowHeight: 19, //自定义行高
          defaultColWidth: 73, //自定义列宽
          config: {
            merge: {}, //合并单元格
            rowlen: {}, //表格行高
            columnlen: {}, //表格列宽
            rowhidden: {}, //隐藏行
            colhidden: {}, //隐藏列
            borderInfo: {}, //边框
            authority: {}, //工作表保护
          },
          scrollLeft: 0, //左右滚动条位置
          scrollTop: 315, //上下滚动条位置
          luckysheet_select_save: [], //选中的区域
          calcChain: [], //公式链
          isPivotTable: false, //是否数据透视表
          pivotTable: {}, //数据透视表设置
          filter_select: {}, //筛选范围
          filter: null, //筛选配置
          luckysheet_alternateformat_save: [], //交替颜色
          luckysheet_alternateformat_save_modelCustom: [], //自定义交替颜色
          luckysheet_conditionformat_save: {}, //条件格式
          frozen: {}, //冻结行列配置
          chart: [], //图表配置
          zoomRatio: 1, // 缩放比例
          image: [], //图片
          showGridLines: 1, //是否显示网格线
          dataVerification: {}, //数据验证配置
          data: [],
          celldata: []
        },
      ],
    }
  
    let newData = JSON.parse(JSON.stringify(this.sheetData))
    newData?.forEach(item => {
      item.celldata = []
      item.data = []
    })
    options.data = this.sheetData
    console.log('luckysheet', this._window.luckysheet);
    
    this._window.luckysheet.create(options)
  }
  //数据对象去重方法
  reduceArr (arrObj) {
    let map = new Map()
    let newArr = arrObj.filter(item => !map.has(item.id) && map.set(item.id, 1))
    return newArr
  }
  //保存
  async save () {
        const jsonData =  this._window.luckysheet.getAllSheets()
        for (let i = 0; i < jsonData.length; i++) {
          //清空data数据，以celldata数据为主
          jsonData[i]["data"] = []
        }
  
        this.reportExcelDto.jsonStr = JSON.stringify( this._window.luckysheet.getAllSheets())
        let setCodeList = []
        // this.dataSet.forEach((code) => {
        //   setCodeList.push(code.id)
        // })
        this.reportExcelDto.setIds = setCodeList.join("|")
        this.reportExcelDto.reportId = '111'
        //保存模板
        this.reportExcelSaveOrUpdateReportExcel()
  }
  async reportExcelSaveOrUpdateReportExcel () {
        // let { code } = await this.$api.reportExcelSaveOrUpdateReportExcel(this.reportExcelDto)
        // if (code == 1) {
          // this.$message.success('保存成功！')
        // }
  }
  async queryAllDataSet () {
    this.outerVisible = true
  }
}
